<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset=UTF-8"">

<link rel="stylesheet" href="${contextPath}/static/statistics/css/bootstrap.min.css" />
<link rel="stylesheet" href="${contextPath}/static/bootstrap/css/bootstrap-table.css" />
<link rel="stylesheet" href="${contextPath}/static/statistics/css/bootstrap-datetimepicker.min.css" />
<link rel="stylesheet" href="${contextPath}/static/statistics/css/combo.select.css" />
<link rel="stylesheet" href="${contextPath}/static/layer/css/layui.css" />
<script src="${contextPath}/static/statistics/js/jquery.js"></script>
<script src="${contextPath}/static/statistics/js/bootstrap.min.js"></script>
<script src="${contextPath}/static/statistics/js/jquery.combo.select.js"></script>
<script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.min.js"></script>
<script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.fr.js"></script>
<script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.zh-CN.js"></script>
<script src=${contextPath}/static/layer/layui.all.js></script>
<script src="${contextPath}/static/util/dateutils.js"></script>

	<style type="text/css">
	.customBtn {
		line-height: 20px;
	    margin-bottom: 3px;
	}
	.btnLine {
		margin-left: 1px; 
		margin-top: 8px;
		margin-bottom: 2px;
	}
	.block{
		min-height: 100px;
	}
	td.enableCli{
		cursor:pointer;
	}
	td.enableCli : hover{
		border-color:#fff;
	}
	.btn-white.btn-warn {
	    border-color: #FF892A ;
	    color: #FF892A !important;
	}
	#scheduling td{
		width:100px;
	}
	input[type="text"]{
		padding:8px;
	}
	.block>span{
		display:block;
	}
	.canselect{
		cursor:pointer;
	}
	.canselect.selected{
		background-color:#ddf0fd;
	}
	.normal{
		background-image:url(${contextPath}/static/image/signin.png);
		background-position:0px 0px;
		background-size:50px 200px;
	}
	.learly{
		background-image: url(/SpringBoot_Dubbo_web/static/image/signin.png);
		background-position: 0px -108px;
		background-size: 50px 200px;
	}
	.late{
		background-image: url(/SpringBoot_Dubbo_web/static/image/signin.png);
		background-position: 0px -54px;
		background-size: 50px 200px;
	}
	.absent{
		background-image: url(/SpringBoot_Dubbo_web/static/image/signin.png);
		background-position: 0px -162px;
		background-size: 50px 200px;
	}
	.signindiv{
		width:50px;
		height:35px;
		position:absolute;
		top:0;
		right:0;
		z-index:100;
	}
</style>
<title>排班管理 - 管理平台</title>
</head>
<body>
<div class="row">
	<div class="row btnLine" >
		<div class="button-len col-sm-12">
			<div class="col-sm-2">
				<input type="text" class="input-sm" style="height:34px;" id="yearMonth" name="YearMonth" placeholder="选择年月" readonly />
			</div>
			<div class="col-sm-3" style="margin-left: 20px;">
				<select id="shop" class="input-sm">
				</select>
			</div>
			<button id="btn_query" class="btn btn-sm btn-white btn-info search-len customBtn">
				<i class="ace-icon fa fa-search orange"></i>搜索
			</button>
		</div>
	</div>
	
	<div class="col-xs-12">
		<div class="clearfix" style="margin:10px 15px 10px 0;"><div class="pull-right" style="text-shadow:1px 1px 1px #ABBAC3">选择当前年份<span id="yearTxt" style="font-size:16px"></span>,月份<span id="monthTxt" style="font-size:16px"></span></div></div>
		<table id="scheduling" class="table table-striped table-condensed table-bordered"></table>
	</div>
</div>
</body>
<script type="text/javascript">
	var TableInit = function () {
    	var oTableInit = new Object();	
    	oTableInit.init = function(){
    		if($("#shop").val() ==null || "" == $("#shop").val()){
    			layer.msg('请选择店铺！');
    			return;
    		}
    		var year = $("#yearTxt").text(),month = $("#monthTxt").text();
    		var fday =1 - oDateUtil.getMonthFirstDayWeek(year,month-1);
    		var trshtml = "<tr><th>周一</th><th>周二</th><th>周三</th><th>周四</th><th>周五</th><th>周六</th><th>周日</th></tr>";
    		for(var i = 0;i < 6;i++){
    			var trhtml = '<tr>';
    			for(var j = 0;j < 7;j++){
    				var dutyDateObj = oDateUtil.getDay(year,month-1,i*7+j+fday+1);
    				if(!oDateUtil.isEnableDay(year,month-1,i*7+j+fday+1)){
    					trhtml +='<td data-day="'+dutyDateObj["a"]+'" class="enableCli" style="color:#999999;position:relative" onclick="showStaffTwo(\''+dutyDateObj["a"]+'\',this)" ><div class="signindiv"></div><div class="block"><span>'+dutyDateObj["b"]+'</span><span class="ns"></span></div></td>'
    				}else{
    					trhtml +='<td data-day="'+dutyDateObj["a"]+'" class="enableCli" onclick="showStaffOne(\''+dutyDateObj["a"]+'\',this)" style="position:relative"><div class="signindiv"></div><div class="block"><span>'+dutyDateObj["b"]+'</span><span class="ns"></span></div></td>'
    				}

    			}
    			trhtml += '</tr>'
    			trshtml += trhtml;
    		}
    		$("#scheduling").html(trshtml);
    		$.ajax({
    			url: '${contextPath}/attendn/getShopUsersDutyList', //localhost:8080
    	        type: 'post',
    	        data:{
    	            "shopId" : $("#shop").val(),
    	            "dutyDate" : year+"-"+month
    		    },
    		    success: function (data) {
					var datainfo = data.data;
					var $tds = $("#scheduling").find("td");
					for(var i = 0;i < datainfo.length;i++){
						$tds.each(function(index,element){
							if(datainfo[i]["DUTY_DATE"] == $(this).attr("data-day")){
								if(datainfo[i]["STATE"]==0){
									$(this).find(".signindiv").addClass("normal");
								}else if(datainfo[i]["STATE"]==1){
									$(this).css("background-color","green");
									$(this).find(".signindiv").addClass("late");
								}else if(datainfo[i]["STATE"]==2){
									$(this).css("background-color","yellow");
									$(this).find(".signindiv").addClass("learly");
								}else if(datainfo[i]["STATE"]==3){
									$(this).css("background-color","red");
									$(this).find(".signindiv").addClass("absent");
								}
								$(this).find(".ns").text(datainfo[i]["UNAMES"]);
								return;
							}
						})
					}
    		    }
    		})
    	}
    	return oTableInit;
	}
	var oDateUtil = new DateUtil();
	var oTable = new TableInit();
	var GLOBAL = {"tdobj":null};
	$("#btn_query").click(function(){
		var yearMonthVal = $('#yearMonth').val();
		if("" != yearMonthVal){
			$("#yearTxt").text(yearMonthVal.split("-")[0])
			$("#monthTxt").text(yearMonthVal.split("-")[1])
		}
		oTable.init();
	})
	$('#yearMonth').datetimepicker({
		format: 'yyyy-mm',
        autoclose: true,
        todayBtn: true,
        startView: 'year',
        minView:'year',
        maxView:'decade',
        language:  'zh-CN'
	}).on('changeDate', function(ev){
	    var date = ev.date;
	    $(this).val(date.getFullYear()+"-"+(date.getMonth()+1))
	});
	function trans2FormatDate(){
		var date = new Date();
		return date.getFullYear()+"-"+(date.getMonth()+1);
	}
	function showStaffOne(dutyDate,tdobj){
		GLOBAL["tdobj"] = tdobj;
		$.ajax({
			url: '${contextPath}/attendn/getshopstaffAndDutyUser', //localhost:8080
	        type: 'post',
	        data:{
	            "shopId" : $("#shop").val(),
	            "dutyDate" : dutyDate
		    },
		    success: function (data) {
		    	var adata = data.data.a;
		    	var bdata = data.data.b;
		    	var cdata = data.data.c;
		    	var cntHtml = '<div style="width:100%;height:100%;overflow:hidden"><ul id="staffOpera" style="width:200%;height:100%;clear:both;">';
		    	cntHtml += '<li data-li="1" style="width:50%;height:100%;float:left;"><div style="width:100%;height:40px;" class="btn-group"><button onclick="staffadd()" type="button" class="btn btn-white btn-sm btn-purple" style="margin:8px 0 0 15px;"><i class="ace-icon fa fa-plus-circle purple"></i>添加</button><button onclick="staffedit()" type="button" class="btn btn-white btn-sm btn-info" style="margin:8px 0 0 15px;"><i class="ace-icon fa fa-pencil blue"></i>修改</button></div><div style="width:100%;height:300px;"><table id="staffinfo" class="table table-striped table-condensed table-bordered"><tr><th>姓名</th><th>上班时间</th><th>下班时间</th><th>备注</th><th>操作</th></tr>';
		    	for(var i = 0;i < bdata.length;i++){
		    		cntHtml +='<tr class="canselect" data-sname="'+bdata[i]["USER_ID"]+'" data-stime="'+bdata[i]["DUTY_BEGIN_TIME"]+'" data-xtime="'+bdata[i]["DUTY_END_TIME"]+'" data-remark="'+(bdata[i]["REMARK"] || "")+'" data-id="'+bdata[i]["ID"]+'"><td class="sname">'+bdata[i]["USER_NAME"]+'</td><td>'+bdata[i]["DUTY_BEGIN_TIME"]+'</td><td>'+bdata[i]["DUTY_END_TIME"]+'</td><td>'+(bdata[i]["REMARK"] || "")+'</td><td><i onclick="staffdelete(\''+bdata[i]["ID"]+'\',this)" class="ace-icon fa fa-trash-o red"></i></td><tr>';
		    	}
		    	cntHtml += '</table><table class="table table-striped table-condensed table-bordered" style="margin-top:10px;"><tr><th>姓名</th><th>签到时间</th><th>签退时间</th></tr>'
			    for(var i = 0;i < cdata.length;i++){
			    	var signinTime = cdata[i]["SIGNIN_TIME"] ? oDateUtil.formatDate(new Date(cdata[i]["SIGNIN_TIME"]),'yyyy-MM-dd hh:mm:ss') : "未签到";
			    	var signoutTime = cdata[i]["SIGNOUT_TIME"] ? oDateUtil.formatDate(new Date(cdata[i]["SIGNOUT_TIME"]),'yyyy-MM-dd hh:mm:ss') : "未签退";
				   	cntHtml +='<tr class="canselect" ><td class="sname">'+cdata[i]["USER_NAME"]+'</td><td>'+signinTime+'</td><td>'+signoutTime+'</td><tr>';
				}
		    	cntHtml += '</table></div></li>';
		    	cntHtml += '<li data-li="2" style="width:50%;height:100%;float:left;"><div style="width:100%;height:300px;padding:10px 15px;"><input id="staffid" type="hidden" value=""/><div class="form-group"><select id="staffselect" class="form-control"  data-live-search="true" title="请选择员工" data-live-search-placeholder="搜索" data-actions-box="true" >'
		    	for(var i = 0;i < adata.length;i++){
		    		cntHtml +='<option value="'+adata[i]["USER_ID"]+'">'+adata[i]["USER_NAME"]+'</option>';
		    	}
		    	cntHtml += '</select></div><div class="form-group"><input id="stime" type="text" class="form-control" placeholder="上班时间" readonly /></div><div class="form-group"><input id="xtime" type="text" class="form-control" placeholder="下班时间" readonly/></div><div class="form-group"><textarea id="remark" class="form-control"></textarea></div><div style="width:100%;height:40px;"><button onclick="staffback()" type="button" class="btn btn-white btn-sm btn-warn" style="margin:8px 0 0 15px;"><i class="ace-icon fa fa-reply orange"></i>返回</button><button onclick="staffsave(\''+dutyDate+'\')" type="button" class="btn btn-white btn-sm btn-info" style="margin:8px 0 0 15px;"><i class="ace-icon fa fa-check blue"></i>保存</button></div></li>';
		    	cntHtml += '</ul></div>';
		    	layer.open({
					type: 1,
					skin: 'layui-layer-rim', //加上边框
				 	area: ['620px', '440px'], //宽高
					content: cntHtml
				});  
		    	initDatetimepicker(["stime","xtime"],dutyDate);
		    	$(".canselect").unbind('click').bind('click',canselectCli);
		    }
		})
	}
	function showStaffTwo(dutyDate,tdobj){
		GLOBAL["tdobj"] = tdobj;
		$.ajax({
			url: '${contextPath}/attendn/getshopSigninAndDutyUser', //localhost:8080
	        type: 'post',
	        data:{
	            "shopId" : $("#shop").val(),
	            "dutyDate" : dutyDate
		    },
		    success: function (data) {
		    	var adata = data.data.a;
		    	var bdata = data.data.b;
		    	var cntHtml = '<div style="width:100%;height:100%;overflow:hidden"><ul id="staffOpera" style="width:100%;height:100%;">';
		    	cntHtml += '<li data-li="1" style="width:100%;height:100%;"><div style="width:100%;height:300px;"><table id="staffinfo" class="table table-striped table-condensed table-bordered" style=""><tr><th>姓名</th><th>上班时间</th><th>下班时间</th><th>备注</th></tr>';
		    	for(var i = 0;i < bdata.length;i++){
		    		cntHtml +='<tr class="canselect" data-sname="'+bdata[i]["USER_ID"]+'" data-stime="'+bdata[i]["DUTY_BEGIN_TIME"]+'" data-xtime="'+bdata[i]["DUTY_END_TIME"]+'" data-remark="'+(bdata[i]["REMARK"] || "")+'" data-id="'+bdata[i]["ID"]+'"><td class="sname">'+bdata[i]["USER_NAME"]+'</td><td>'+bdata[i]["DUTY_BEGIN_TIME"]+'</td><td>'+bdata[i]["DUTY_END_TIME"]+'</td><td>'+(bdata[i]["REMARK"] || "")+'</td><tr>';
		    	}
		    	cntHtml += '</table><table class="table table-striped table-condensed table-bordered" style="margin-top:10px;"><tr><th>姓名</th><th>签到时间</th><th>签退时间</th></tr>'
		    	for(var i = 0;i < adata.length;i++){
		    		var signinTime = adata[i]["SIGNIN_TIME"] ? oDateUtil.formatDate(new Date(adata[i]["SIGNIN_TIME"]),'yyyy-MM-dd hh:mm:ss') : "未签到";
		    		var signoutTime = adata[i]["SIGNOUT_TIME"] ? oDateUtil.formatDate(new Date(adata[i]["SIGNOUT_TIME"]),'yyyy-MM-dd hh:mm:ss') : "未签退";
			    	cntHtml +='<tr class="canselect" ><td class="sname">'+adata[i]["USER_NAME"]+'</td><td>'+signinTime+'</td><td>'+signoutTime+'</td><tr>';
			    }
		    	cntHtml +='</table></div></li>';
		    	cntHtml += '</ul></div>';
		    	layer.open({
					type: 1,
					skin: 'layui-layer-rim', //加上边框
				 	area: ['620px', '440px'], //宽高
					content: cntHtml
				});  
		    }
		})
	}
	function getShop(){
		$.ajax({
	        url: '${contextPath}/attendn/getShops', //localhost:8080
	        data:{},
	        type: 'post',
	        success: function (data) {
	           	var data = data.data;
				var dstore = '<optgroup label="直营" data-icon="glyphicon-ok">',nstore = '<optgroup label="加盟" data-icon="glyphicon-ok">';
	        	for(var i = 0;i < data.length;i++){
	        		if('直营' == data[i]["shopType"]){
	        			dstore +='<option value="'+data[i]["shopId"]+'">'+data[i]["shopName"]+'</option>';
	        		}
					if('加盟' == data[i]["shopType"]){
						nstore +='<option value="'+data[i]["shopId"]+'">'+data[i]["shopName"]+'</option>';
	        		}
	        	}
	        	dstore += '</optgroup>';
	        	nstore += '</optgroup>';
	        	$("#shop").html(dstore+nstore);
	        	$('#shop').comboSelect();
	        },
	        error: function (error) {
	            alert(error)
	        }
	    })
	}
	function staffadd(){
		var width = $("#staffOpera").parent().css("width");
		$("#staffOpera").animate({marginLeft:"-"+width});
	}
	function staffback(){
		$("#staffid").val("")
		$("#stime").val("")
		$("#xtime").val("")
		$("#remark").val("")
		$("#staffOpera").animate({marginLeft:0});
	}
	function staffedit(){
    	if($(".canselect.selected").length == 0){
    		layer.msg('未选中具体行！');
    		return;
    	}
		$("#staffid").val($(".canselect.selected").attr("data-id"));
		$("#stime").val($(".canselect.selected").attr("data-stime"));
		$("#xtime").val($(".canselect.selected").attr("data-xtime"));
		$("#remark").val($(".canselect.selected").attr("data-remark"));
		$("#staffselect").val($(".canselect.selected").attr("data-sname"));
		//$('#staffselect').comboSelect();
		var width = $("#staffOpera").parent().css("width");
		$("#staffOpera").animate({marginLeft:"-"+width});
		
	}
	function staffsave(dutyDate){
		$("#staffid").val() == "" ? staffaddtrigger(dutyDate) : staffedittrigger(dutyDate);
	}
	function staffaddtrigger(dutyDate){
		var ifexist = false;
		$(".canselect").each(function(){
			if($(this).attr("data-sname") == $("#staffselect").val()){
				ifexist = true
				return;
			}
		})
		if(ifexist){
			layer.msg("已安排该职工值日,请重新选择！");
			return;
		}
		var staffselect = $("#staffselect").find("option:selected").text();
		var stime = $("#stime").val();
		var xtime = $("#xtime").val();
		var remark = $("#remark").val();
		$.ajax({
			url: '${contextPath}/attendn/insertShopUserDuty', //localhost:8080
	        type: 'post',
	        data:{
	            "shopId" : $("#shop").val(),
	            "userId" : $("#staffselect").val(),
	            "dutyBeginTime" : stime,
	            "dutyEndTime" : xtime,
	            "remark" : remark,
	            "dutyDate": dutyDate
		    },
		    success: function (data) {
		    	if(data.success){
			    	$("#staffinfo").append('<tr class="canselect" data-sname="'+$("#staffselect").val()+'" data-stime="'+stime+'" data-xtime="'+xtime+'" data-remark="'+remark+'" data-id="'+data.data+'"><td class="sname">'+staffselect+'</td><td>'+stime+'</td><td>'+xtime+'</td><td>'+remark+'</td><td><i onclick="staffdelete(\''+data.data+'\',this)" class="ace-icon fa fa-trash-o red"></i></td><tr>');
					var nameTxt = "";
					$(".sname").each(function(index,element){
						nameTxt += $(this).text()+",";
					})
					$(GLOBAL["tdobj"]).find(".ns").text(nameTxt.substring(0,nameTxt.length-1));
					$(".canselect").unbind('click').bind('click',canselectCli);
		    	}
		    	layer.msg(data.message);
		    }
		})
	}
	function staffdelete(deleteId,that){
		$.ajax({
			url: '${contextPath}/attendn/deleteShopUserDutyById', //localhost:8080
	        type: 'post',
	        data:{
	        	"id" : deleteId,
		    },
		    success: function (data) {
		    	if(data.success){
			    	$(that).parent().parent().remove();
					var nameTxt = "";
					$(".sname").each(function(index,element){
						nameTxt += $(this).text()+",";
					})
					$(GLOBAL["tdobj"]).find(".ns").text(nameTxt.substring(0,nameTxt.length-1));
					$(".canselect").unbind('click').bind('click',canselectCli);
		    	}
		    	layer.msg(data.message);
		    }
		})
	}
	function staffedittrigger(dutyDate){
		var staffselect = $("#staffselect").find("option:selected").text();
		var stime = $("#stime").val();
		var xtime = $("#xtime").val();
		var remark = $("#remark").val();
		$.ajax({
			url: '${contextPath}/attendn/updateShopUserDuty', //localhost:8080
	        type: 'post',
	        data:{
	        	"id" : $("#staffid").val(),
	            "userId" : $("#staffselect").val(),
	            "dutyBeginTime" : stime,
	            "dutyEndTime" : xtime,
	            "remark" : remark
		    },
		    success: function (data) {
		    	if(data.success){
			    	var $trselected = $(".canselect.selected");
			    	var $tdselected = $trselected.find("td");
			    	$trselected.attr("data-sname",staffselect);
			    	$trselected.attr("data-stime",stime);
			    	$trselected.attr("data-xtime",xtime);
			    	$trselected.attr("data-remark",remark);
			    	$tdselected.eq(0).html(staffselect);
			    	$tdselected.eq(1).html(stime);
			    	$tdselected.eq(2).html(xtime);
			    	$tdselected.eq(3).html(remark);
					var nameTxt = "";
					$(".sname").each(function(index,element){
						nameTxt += $(this).text()+",";
					})
					$(GLOBAL["tdobj"]).find(".ns").text(nameTxt.substring(0,nameTxt.length-1));
					$(".canselect").unbind('click').bind('click',canselectCli);
		    	}
		    	layer.msg(data.message);
		    }
		})
	}

	function initDatetimepicker(arr,dutyDate) {
		arr.forEach(function(item, index, input) {
			$('#' + item).datetimepicker({
				language : 'zh-CN',
				weekStart : 1,
				todayHighlight : 1,
				startView : 1,
				minuteStep : 1,
				forceParse : 0,
				showMeridian : 1,
				format : "yyyy-mm-dd hh:ii:ss",
				autoclose : true,
				initialDate : new Date(dutyDate)
			})
		})
	}
	function canselectCli(){
		$(".canselect").removeClass("selected");
		$(this).addClass("selected");
	}
	$(function(){
		var date = new Date();
		$("#yearTxt").text(date.getFullYear())
		$("#monthTxt").text(date.getMonth()+1)
		getShop();
		oTable.init();
		$("#yearMonth").val(trans2FormatDate());
	})
</script>
</html>